﻿
namespace Mulala.Cavan.Presentation.Mvc.Controller
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Mulala.Cavan.Presentation.Seedwork;
    using Mulala.Cavan.Domain.MainBoundedContext.ProprietorModule;
    using Mulala.Cavan.Domain.MainBoundedContext.SearchModule;
    using Mulala.Cavan.Application.MainBoundedContext.ProprietorModule;
    using System.Web.Mvc;
    using Mulala.Cavan.Presentation.Mvc.ViewModel;
    using Mulala.Cavan.Domain.MainBoundedContext.ConsignModule;
    using Mulala.Cavan.Domain.Seedwork;
    using Mulala.Cavan.Application.MainBoundedContext.AttachmentModule;
    using Mulala.Cavan.Core.Settings;
    using Mulala.Cavan.Domain.MainBoundedContext.AttachmentModule;
    using Mulala.Cavan.Application.MainBoundedContext.ConsignModule;
    using Mulala.Cavan.Domain.MainBoundedContext.Setting;
    using Mulala.Cavan.Domain.MainBoundedContext.NannyModule;
    using Mulala.Cavan.Domain.MainBoundedContext.SecurityModule;
    using Mulala.Cavan.Domain.MainBoundedContext.InformationModule;
    using Mulala.Cavan.Application.MainBoundedContext.InformationModule;

    public class ProprietorCenterController : EntityController<Proprietor, ProprietorSearch, IProprietorViewModel, IProprietorAppService>, IProprietorCenterController
    {
        private IAttachmentAppService AttachmentAppService { get; set; }
        private IFileUploadAppService FileUploadAppService { get; set; }
        private IConsignAppService ConsignAppService { get; set; }
        private IUserMessageAppService UserMessageAppService { get; set; }

        public ProprietorCenterController()
        {
            this.Model = new ProprietorViewModel();
        }

        public override string ControllerName
        {
            get { return ControllerConst.PROPRIETORCENTER; }
        }

        public override bool UseDenied
        {
            get { return true; }
        }

        [ActionName(ActionConst.INDEX)]
        public ActionResult GetUserCenterInfo()
        {
            Proprietor proprietor = this.AppService.GetById(this.Model.MasterModel.CurrentUserModel.UserAccountID);
            IProprietorViewModel proprietorViewModel = ProprietorViewModelConverter.Convert(proprietor);
            return View(proprietorViewModel);
        }

        [HttpGet]
        [ActionName(ActionConst.INFO)]
        public ActionResult GetProprietorInfo()
        {
            Proprietor proprietor = this.AppService.GetById(this.Model.MasterModel.CurrentUserModel.UserAccountID);
            IProprietorViewModel proprietorViewModel = ProprietorViewModelConverter.Convert(proprietor);

            return View(proprietorViewModel);
        }

        [HttpPost]
        [ActionName(ActionConst.INFO)]
        public JsonResult UpdateProprietorInfo(IProprietorViewModel proprietorViewModel)
        {
            BoolGenericResult<Proprietor> result =  this.AppService.Update(proprietorViewModel.Item);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [HttpGet]
        [ActionName(ActionConst.AVATAR)]
        public ActionResult GetProprietorAvatar()
        {
            IProprietorAvatarViewModel model = ModelFactory.CreateModel<IProprietorAvatarViewModel>();
            Proprietor proprietor = ProprietorFactory.CreateProprietor(this.Model.MasterModel.CurrentUserModel.UserAccountID);
            model.Avatar = this.AttachmentAppService.GetProprietorAvatar(proprietor);
            if (this.HttpContext.Request["img"] != null)
            {
                model.Avatar = this.HttpContext.Request["img"].ToString();
            }
            return View(model);
        }

        [ActionName(ActionConst.AVATAR)]
        public JsonResult UpdateProprietorAvatar(ProprietorAvatarViewModel proprietorAvatar)
        {
            string temp = proprietorAvatar.Avatar.Replace(Global.Settings.TempImageServer, "").Replace("%C3%97", "×");
            string directory = temp.Substring(0, temp.LastIndexOf('/') + 1);
            string oldFileName = temp.Substring(directory.LastIndexOf('/') + 1);
            string newFileName = "avatar" + oldFileName;
            FileUploadAppService.CutPhoto(AttachmentIdentifier.AttachmentGroup.ProprietorAvatar.GetHashCode(), directory, oldFileName, newFileName, proprietorAvatar.Width, proprietorAvatar.Height, proprietorAvatar.X, proprietorAvatar.Y);
            FileUploadAppService.CopyFile(directory, newFileName);

            Proprietor proprietor = this.AppService.GetById(this.Model.MasterModel.CurrentUserModel.UserAccountID);
            Attachment avatar = this.AttachmentAppService.GetProprietorAvatar(proprietor.ID);
            proprietor.Attachments = new List<Attachment>();
            if (null != avatar)
            {
                proprietor.Attachments.Add(avatar);
            }
            BoolGenericResult<Attachment> result = this.AppService.UpdateProprietorAvatar(proprietor, directory, newFileName);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName("consigns")]
        public ActionResult GetConsigns(int cp)
        {
            IDictionary<string, bool> orderBy = new Dictionary<string, bool>();
            orderBy.Add("CreateTime", true);
            IConsignsViewModel consignsViewModel = ModelFactory.CreateModel<IConsignsViewModel>();
            ConsignSearch consignSearch = ConsignSearchFactory.CreateConsignSearch(this.Model.MasterModel.CurrentUserModel.UserAccountID, orderBy, cp, Project.Settings.MaxRowsPerPage);
            IList<Consign> consigns = this.ConsignAppService.GetBySearch(consignSearch).ToList();
            consignsViewModel.Consigns =  ConsignViewModelConverter.Convert(consigns);

            return View(consignsViewModel);
        }

        [ActionName("biddingconsigns")]
        public JsonResult GetConsigns()
        {
            IDictionary<string, bool> orderBy = new Dictionary<string, bool>();
            orderBy.Add("CreateTime", true);
            IConsignsViewModel consignsViewModel = ModelFactory.CreateModel<IConsignsViewModel>();
            ConsignSearch consignSearch = ConsignSearchFactory.CreateConsignSearch(this.Model.MasterModel.CurrentUserModel.UserAccountID, ConsignIdentifier.ConsignStatus.IsBidding, orderBy, 1, Project.Settings.MaxRowsPerPage);
            IList<Consign> consigns = this.ConsignAppService.GetBySearch(consignSearch).ToList();

            List<SelectListItem> consignItems = new List<SelectListItem>();
            consignItems.Add(new SelectListItem { Text = "请选择", Value = "0", Selected = true });
            foreach (Consign c in consigns)
            {
                consignItems.Add(new SelectListItem { Text = c.Name, Value = c.ID.ToString() });
            }
            var jsonConsigns = new { Consigns = consignItems };

            return Json(jsonConsigns);
        }

        [ActionName("consignbidders")]
        public ActionResult GetConsignBidders(int cp)
        {
            IProprietorBiddedConsignViewModel proprietorBiddedConsignViewModel = ModelFactory.CreateModel<IProprietorBiddedConsignViewModel>();
            IList<ConsignBidder> consignBidders = this.ConsignAppService.GetConsignBiddersByProprietor(this.Model.MasterModel.CurrentUserModel.UserAccountID);
            proprietorBiddedConsignViewModel.ConsignBidders = ConsignBidderViewModelConverter.Convert(consignBidders);

            return View(proprietorBiddedConsignViewModel);
        }

        [HttpGet]
        [ActionName("publishconsign")]
        public ActionResult UpdateConsign(int? id)
        {
            IConsignViewModel consignViewModel = ModelFactory.CreateModel<IConsignViewModel>();
            if (id.HasValue)
            {
                Consign consign = this.ConsignAppService.GetById(id.Value);
                consignViewModel.Item = consign;
                ConsignViewModelConverter.ConvertForEdit(consignViewModel, consign);
            }

            return View(consignViewModel);
        }

        [HttpPost]
        [ActionName("publishconsign")]
        public ActionResult UpdateConsign(ConsignViewModel consignViewModel)
        {
            ConsignViewModelConverter.ConvertForEdit(consignViewModel.Item, consignViewModel);
            BoolGenericResult<Consign> result = new BoolGenericResult<Consign>();
            if (consignViewModel.Item.ID > 0)
            {
                result = this.ConsignAppService.Update(consignViewModel.Item);
            }
            else
            {
                result = this.ConsignAppService.Add(consignViewModel.Item);
            }

            return RedirectToAction("publishconsign", new { id = result.Object.ID });
        }

        [ActionName("deleteconsign")]
        public JsonResult DeleteConsign(int id)
        {
            BoolGenericResult<Consign> result = this.ConsignAppService.UpdateConsignStatus(ConsignFactory.CreateConsign(id), ConsignIdentifier.ConsignStatus.IsDeleted);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName("cancelconsign")]
        public JsonResult UpdateConsignByCancel(int id)
        {
            BoolGenericResult<Consign> result = this.ConsignAppService.UpdateConsignStatus(ConsignFactory.CreateConsign(id), ConsignIdentifier.ConsignStatus.IsCanceled);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName("resumeconsign")]
        public JsonResult UpdateConsignByResume(int id)
        {
            BoolGenericResult<Consign> result = this.ConsignAppService.UpdateConsignStatus(ConsignFactory.CreateConsign(id), ConsignIdentifier.ConsignStatus.IsBidding);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName("lockconsign")]
        public JsonResult UpdateConsignByLock(int id)
        {
            BoolGenericResult<Consign> result = this.ConsignAppService.UpdateConsignStatus(ConsignFactory.CreateConsign(id), ConsignIdentifier.ConsignStatus.IsLocked);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName("unlockconsign")]
        public JsonResult UpdateConsignByUnlock(int id)
        {
            BoolGenericResult<Consign> result = this.ConsignAppService.UpdateConsignStatus(ConsignFactory.CreateConsign(id), ConsignIdentifier.ConsignStatus.IsBidding);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName("designatenanny")]
        public JsonResult AddConsignBidder(int id1, int id2)
        {
            Consign consign = ConsignFactory.CreateConsign(id1);
            Nanny nanny = NannyFactory.CreateNanny(id2);
            Proprietor proprietor = ProprietorFactory.CreateProprietor(this.Model.MasterModel.CurrentUserModel.UserAccountID);
            BoolGenericResult<ConsignBidder> result = this.ConsignAppService.AddConsignBidderByProprietor(consign, nanny, proprietor);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName("acceptnanny")]
        public JsonResult UpdateConsignBidderToAccepted(int id, int nannyId)
        {
            BoolGenericResult<ConsignBidder> result = this.ConsignAppService.UpdateConsignBidderStatusToAccept(ConsignFactory.CreateConsign(id), NannyFactory.CreateNanny(nannyId));

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName("leavemessage")]
        public JsonResult AddMessage(UserMessageViewModel userMessageViewModel)
        {
            userMessageViewModel.Item.MessagerUser.ID = this.Model.MasterModel.CurrentUserModel.UserAccountID;
            userMessageViewModel.Item.MessagerUser.Roles.Add(RoleFactory.CreateRole(SecurityIdentifier.Role.Proprietor.GetHashCode()));
            BoolGenericResult<UserMessage> result = this.UserMessageAppService.Add(userMessageViewModel.Item);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }

        [ActionName("reply")]
        public JsonResult AddMessageReply(UserMessageViewModel userMessageViewModel)
        {
            userMessageViewModel.Item.MessagerUser.ID = this.Model.MasterModel.CurrentUserModel.UserAccountID;
            userMessageViewModel.Item.MessagerUser.Roles.Add(RoleFactory.CreateRole(SecurityIdentifier.Role.Proprietor.GetHashCode()));
            BoolGenericResult<UserMessage> result = this.UserMessageAppService.AddUserMessageReply(userMessageViewModel.Item);

            BoolResult jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult);
        }
    }
}
